//
//  ZNWBHomeViewController.swift
//  ZNWeibo
//
//  Created by FunctionMaker on 2017/7/28.
//  Copyright © 2017年 FunctionMaker. All rights reserved.
//

import UIKit

/// 原创微博CellID
private let normalCellID = "HOME_CELL_NORMAL"
/// 转发微博CellID
private let retweetedCellID = "HOME_CELL_RETWEETED"

class ZNWBHomeViewController: ZNWBBaseViewController {
    fileprivate lazy var listViewModel = ZNWBStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
    }
}

extension ZNWBHomeViewController {
    fileprivate func setupUI() {
        if ZNWBNetworkManager.shared.isLogin {
            zn_navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends), event: .touchUpInside)
        } else {
            zn_navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", fontSize: 16, target: self, normalColor: UIColor.orange, highlightedColor: UIColor.darkGray, action: #selector(register), event: .touchUpInside, isBack: false)
            zn_navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登录", fontSize: 16, target: self, normalColor: UIColor.orange, highlightedColor: UIColor.darkGray, action: #selector(login), event: .touchUpInside, isBack: false)
        }
        
        // 去除cell的分割线
        tableView?.separatorStyle = .none
        
        // 注册cell
        tableView?.register(UINib(nibName: "ZNWBNormalStatusCell", bundle: nil), forCellReuseIdentifier: normalCellID)
        tableView?.register(UINib(nibName: "ZNWBRetweetedStatusCell", bundle: nil), forCellReuseIdentifier: retweetedCellID)
        
        // iOS8后动态计算cell高度，缓存Cell高度就不在需要自动计算
//        tableView?.rowHeight = UITableViewAutomaticDimension
//        tableView?.estimatedRowHeight = 600
        
        let title = ZNWBNetworkManager.shared.userAccount.screen_name
        let button = ZNWBTitleButton(title: title);
        
        button.addTarget(self, action: #selector(titleSelected), for: .touchUpInside)
        
        zn_navigationItem.titleView = button
    }
    
    @objc private func titleSelected(sender: UIButton) {
        sender.isSelected = !sender.isSelected
    }
    
    //FIXME: - 未完成
    @objc private func showFriends() {
        let vc = ZNWBBaseViewController()
        
        navigationController?.pushViewController(vc, animated: true)
    }
}

extension ZNWBHomeViewController {
    override func loadData() {
        
        refreshControl?.beginRefreshing()
        
        listViewModel.loadStatuses(isShouldPullUp: isShouldPullUpRefresh) { (isSuccessful, newCount) in
            if isSuccessful {
                print("刷新数据完成")
                
                if !self.isShouldPullUpRefresh {
                    self.tabBarItem.badgeValue = newCount > 0 ? "\(newCount)" : nil
                    UIApplication.shared.applicationIconBadgeNumber = newCount
                }
                
                self.refreshControl?.endRefreshing()
                
                self.tableView?.reloadData()
            } else {
                print("刷新失败")
            }
            
            //下拉刷新次数有限
            self.isShouldPullUpRefresh = false
        }
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 此方法会多次调用？之前在OC中测试发现是有多少cell就会调用几次，在Swift中不是这样，但还是会重复调用几次。费解
        
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 根据ID选择不同的cell
        let viewModel = listViewModel.statusList[indexPath.row]
        let cellID = (viewModel.status.retweeted_status != nil) ? retweetedCellID : normalCellID
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! ZNWBStatusCell
    
        cell.model = viewModel
        cell.delegate = self
        
        print("cell");
            
        return cell
    }
    
    // 一次性将所有的cell的高度获取完毕，然后再调用cellForRows绘制cell，并还会调用此方法？费解
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let viewModel = listViewModel.statusList[indexPath.row];
        print("height")
        return viewModel.cacheRowHeight
    }
}

extension ZNWBHomeViewController: ZNWBStatusCellDelegate {
    func statusCellDidSelectedURLString(cell: ZNWBStatusCell, urlString: String) {
        let webViewController = ZNWBWebViewController()
        webViewController.urlString = urlString
        
        navigationController?.pushViewController(webViewController, animated: true)
    }
}
